package org.example.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.example.model.User;
import org.example.service.UserService;
import org.example.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    /*https://www.bilibili.com/video/BV18g4y1z7rL?p=37*/
    /*https://www.baizhiedu.xin/front/index#/main*/
    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(User user){
        log.info("用户名"+user.getName());
        log.info("密码"+user.getPassword());
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        try{
            User login = userService.login(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("id",login.getId());
            payload.put("name",login.getName());
            //生成JWT令牌
            String token = JWTUtils.getToken(payload);
            objectObjectHashMap.put("token",token);
            objectObjectHashMap.put("state",true);
            objectObjectHashMap.put("msg","认证成功");
        }catch (Exception e){
            objectObjectHashMap.put("state",false);
            objectObjectHashMap.put("msg","认证失败");
        }
        return objectObjectHashMap;
    }

    @PostMapping("/user/test")
    public Map<String,Object> test(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();

        String token = request.getHeader("token");
        DecodedJWT decodedJWT = JWTUtils.tokeInfo(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        log.info("name"+String.valueOf(claims.get("name").asString()));
        log.info("id"+String.valueOf(claims.get("id").asString()));

        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }
}
